package com.xncoding.jwt.interceptor;

import com.xncoding.jwt.commons.SocketConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * socket针对各个业务模块会话链接处理类
 *
 * @author feilong
 * @version 1.0
 * @since 2024/5/29
 */
@Component
public class WebSocketInterceptor implements HandshakeInterceptor {
    private Logger log = LoggerFactory.getLogger(this.getClass());


    /**
     * 握手前拦截
     * <p>
     * 此处可用于会话链接前进行token校验
     *
     * @param request          用于接收用户请求参数
     * @param response         用于处理响应数据
     * @param socketHandler    用于处理会话动作的核心处理类
     * @param socketAttributes 用于放置会话参数
     * @return
     * @throws Exception
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                   WebSocketHandler socketHandler, Map<String, Object> socketAttributes) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            if (log.isInfoEnabled()) {
                log.info("start beforeHandshake");
            }
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            HttpServletRequest httpRequest = servletRequest.getServletRequest();
            String connectUserId = httpRequest.getParameter(SocketConstants.MESSAGE_SERVICE_USER_ID_PARAM);
            if (connectUserId == null || "".equals(connectUserId)) {
                log.error("connect param[{}] can not be null,please check! ",
                        SocketConstants.MESSAGE_SERVICE_USER_ID_PARAM);
                return false;
            }
            socketAttributes.put(SocketConstants.MESSAGE_SERVICE_USER_ID_PARAM, connectUserId);
            if (log.isInfoEnabled()) {
                log.info("finish beforeHandshake");
            }
        }
        return true;
    }

    /***
     * 处理握手后拦截的动作
     *
     * @param serverHttpRequest 用于接收请求参数
     * @param serverHttpResponse  用于处理响应数据
     * @param socketHandler 用于处理会话动作的核心处理类
     * @param exception  用于处理核心异常
     */
    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest,
                               ServerHttpResponse serverHttpResponse,
                               WebSocketHandler socketHandler,
                               Exception exception) {
        log.info("afterHandshake完成");
    }
}
